<template>
  <div class="blogBodyRight-container">
    <h2>目录</h2>
    <BlogList :list="addListSelected" @select="handleSelect($event)" />
  </div>
</template>

<script>
import BlogList from "../../BlogList/list.vue";
export default {
  components: {
    BlogList,
  },
  props: {
    List: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      activeAnchor: "",
    };
  },
  computed: {
    // 给传入的List数据的每个对象添加isselect属性并返回一个带有isselect的新数据
    addListSelected() {
      const getList = (list = []) => {
        return list.map((item) => {
          return {
            ...item,
            isSelect: item.anchor === this.activeAnchor,
            children: getList(item.children),
          };
        });
      };
      return getList(this.List);
    },
    //根据list的anchor获取他们对应元素的数组
    doms() {
      const doms = [];
      const getDoms = (list) => {
        for (const item of list) {
          doms.push(document.getElementById(item.anchor));
          if (item.children) {
            getDoms(item.children);
          }
        }
      };
      getDoms(this.List);
     
      return doms
    },
  },
  created() {
    this.$bus.$on('MainScroll',this.setActiveAnchor)
  },
  
  destroyed() {
    this.$bus.$off('MainScroll',this.setActiveAnchor) 
  },
  

  methods: {
    handleSelect(item) {
      location.hash = item.anchor;
    },
    //设置activeAnchor为正确的值
    setActiveAnchor() {
        const top=200;
            this.activeAnchor=''
        for (const dom of this.doms) {
            if(!dom){
                continue;
            }
            //元素离视口顶端的距离.getBoundingClientRect();
             const domTop=dom.getBoundingClientRect().top;
            if(domTop>=0&& domTop<top){
                // 在规定的范围内
                this.activeAnchor=dom.id;
                return;
            }else if(domTop>top){
                //在规定的范围下方
                return
            }else {
                //在规定饭为的上方
                this.activeAnchor=dom.id;
            }

            


        }
    },
  },
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
.blogBodyRight-container {
  position: relative;
  width: 300px;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  overflow: auto;
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
  }
}
</style>